﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;

namespace BPMS.Core.DataAccess
{
    public class DbConnectionProvider : IDisposable
    {
        private readonly DbConnection Connection;
        private bool isDisposed = false;
        public DbConnectionProvider(DbProviderFactory providerFactory, string connectionString)
        {
            Connection = providerFactory.CreateConnection();
            Connection.ConnectionString = connectionString;
        }

        public void CloseConnection()
        {
            if (null != Connection)
            {
                if (Connection.State != ConnectionState.Closed)
                {
                    Connection.Close();
                }
                Connection.Dispose();
            }
        }

        public DbConnection OpenConnection()
        {
            if (null != Connection)
            {
                if (Connection.State != ConnectionState.Open)
                {
                    Connection.Open();
                }
            }
            return Connection;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        public void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                if (!isDisposed)
                {
                    CloseConnection();
                    isDisposed = true;
                }
            }
        }
    }
}
